from .functions import ( make_mask, int_to_twos, twos_to_int, sign_extend )
import sys

# we may need arbitrary-sized integers, so let's be safe
num_type = long if sys.version_info[0] == 2 else int

class FixedInt(num_type):

    #extending immutable types is complex
    def __new__(cls, val, **kw):
        bits = kw.get('bits', 32)
        val = int_to_twos(val, bits)
        inst = super(FixedInt, cls).__new__(cls, val)
        inst.bits = bits
        inst.overflow = False
        return inst

    def __len__(self):
        return self.bits

    def __setitem__(self, bit, val):
        if isinstance(bit, slice):
            # will stepping ever be needed? I doubt it.
            assert bit.step is None
            sz = abs(bit.start - bit.stop)
            val = type(self)(val, sz)
            ~make_mask(bit.start, bit.stop)

    def __getitem__(self, bit):
        if isinstance(bit, slice):
            # will stepping ever be needed? I doubt it.
            assert bit.step is None
            start, end = self.bits - bit.start, self.bits - bit.stop
            ret = self & make_mask(start, end)
            ret >>= min(start, end)
            sz = start - end
            if sz < 0: ret = type(self)(ret, bits=-sz).reverse()
            else: ret=type(self)(ret, bits=sz)
            return ret

    def reverse(self):
        new = 0
        old = num_type(self)
        idx = 0

        while old:
            print old, new
            new |= old & 1
            old >>= 1
            if old: new <<= 1


        return type(self)(new, bits=len(self))
